﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using SocialNetwork;
using SocialNetwork.Models;
using System.Web.Configuration;
using System.Web.Mvc;
namespace SocialNetwork.Models
{
    public class UserRepository // для допоміжних функцій і взаємодії з БД та "aMembershipProvider'ом"
    {
        private DBModel _db;
        public DBModel db
        {
            get
            {
                if (_db == null)
                    _db = new DBModel();
                return _db;
            }
        }

        public bool CreateUser(RegisterModel newUser, string roleName)
        {
            var role = GetRole(roleName);
            try
            {
                var user = new User
                    {
                        Id = Guid.NewGuid(),
                        Username = newUser.UserName,
                        Email = newUser.Email,
                        Password = FormsAuthentication.HashPasswordForStoringInConfigFile(newUser.Password, "md5"),
                        IsOnline = true,
                        RegDate = DateTime.Now,
                        LoginDate = DateTime.Now,
                        LogoffDate = DateTime.Now,
                        RoleId = role.Id
                    };

                db.AddToUser(user);
                db.SaveChanges();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        #region Transforming

        //public static explicit operator MUser(User entityUser)
        //{
        //    var user = new MUser()
        //    {
        //        id = entityUser.Id,
        //        roleId = entityUser.RoleId,
        //        username = entityUser.Username,
        //        email = entityUser.Email,
        //        password = entityUser.Password,
        //        firstName = entityUser.FirstName,
        //        lastName = entityUser.LastName,
        //        nickname = entityUser.Nickname,
        //        age = entityUser.Age ?? 0,
        //        sex = entityUser.Sex,
        //        mood = entityUser.Mood,
        //        avatara = entityUser.Avatara,
        //        homeAddress = entityUser.HomeAddress,
        //        hobbies = entityUser.Hobbies,
        //        jobPlace = entityUser.JobPlace,

        //        regDate = entityUser.RegDate,
        //        loginDate = entityUser.LoginDate,
        //        logoffDate = entityUser.LogoffDate
        //    };
        //    return user;
        //}

        //public static explicit operator User(MUser mUser)
        //{
        //    return new User()
        //    {
        //        Id = mUser.id,
        //        RoleId = mUser.roleId,
        //        Username = mUser.username,
        //        Email = mUser.Email,
        //        Password = mUser.password,
        //        FirstName = mUser.firstName,
        //        LastName = mUser.lastName,
        //        Nickname = mUser.nickname,
        //        Age = mUser.age ?? 0,
        //        Sex = mUser.sex,
        //        Mood = mUser.mood,
        //        Avatara = mUser.avatara,
        //        HomeAddress = mUser.homeAddress,
        //        Hobbies = mUser.hobbies,
        //        JobPlace = mUser.jobPlace,

        //        RegDate = mUser.regDate,
        //        LoginDate = mUser.loginDate,
        //        LogoffDate = mUser.logoffDate
        //    };
        //}

        #endregion

        //public LogOnModel model=new LogOnModel();
        //public  User GetCurrentUser()
        //{
        //    return GetUser(model.UserName);
       // }
        public User GetUser(Guid id)
        {
            return db.User.FirstOrDefault(x => x.Id == id);
        }

        public User GetUser(string username)
        {
            return db.User.FirstOrDefault(x => x.Username == username);
        }

        public IEnumerable<User> GetAllUsers()
        {
            var users = db.User.AsEnumerable().OrderBy(x => x.Username);
            return users;
        }

        public IEnumerable<User> GetUsersByCondition(Func<User, bool> predicate, Func<User, object> orderby)
        {
            return db.User.Where(predicate).OrderBy(orderby);
        }

        public bool DeleteUser(Guid id)
        {
            if (!UserExists(id))
                return false;
            db.User.DeleteObject(GetUser(id));
            return true;
        }

        public bool DeleteUser(string username)
        {
            if (!UserExists(username))
                return false;
            db.User.DeleteObject(GetUser(username));
            return true;
        }

        public Role GetRole(string roleName)
        {
            var role = db.Role.FirstOrDefault(x => x.Name == roleName);
            return role;
        }

        public bool ChangePassword(string username, string newPassword)
        {
            var user = GetUser(username);
            user.Password = newPassword;

            db.SaveChanges();
            return true;
        }

        #region  Availability

        public bool UserExists(string login)
        {
            var user = db.User.FirstOrDefault(x => x.Username == login);

            return (user == null) ? false : true;
        }

        public bool UserExists(Guid id)
        {
            return db.User.Any(x => x.Id == id);
        }

        public bool EmailExists(string email)
        {
            return db.User.Any(x => x.Email == email);
        }

        public string GetUserNameByEmail(string email)
        {
            var user = db.User.FirstOrDefault(x => x.Email == email);

            return user.Username ?? null;
        }

        public User GetUserByEmail(string email)
        {
            var user = db.User.FirstOrDefault(x => x.Email == email);

            return user ?? null;
        }
        #endregion

        public Role GetRoleForUser(string username)
        {
            var role = from user in db.User
                       where user.Username == username
                       select user.Role;
            return role.First();
        }

        public bool RoleExists(Role role)
        {
            return db.Role.Any(x => x.Name == role.Name);
        }

        public void CreateRole(string roleName)
        {
            var role = Role.CreateRole(new Guid(), roleName);
            db.AddToRole(role);
        }

        public void DeleteRole(string roleName)
        {
            var role = db.Role.FirstOrDefault(x => x.Name == roleName);
            if (roleName != null)
                db.Role.DeleteObject(role);
        }

        public bool ValidateUsername(string username)
        {
            return GetAllUsers().Any(user => user.Username == username);
        }
    }
}